package com.home.fansea.controller;

import com.home.fansea.annotation.RedisLock;
import com.home.fansea.entity.Products;
import com.home.fansea.entity.Result;
import com.home.fansea.mapper.ProductsMapper;
import com.home.fansea.service.ProductsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import static jodd.util.ThreadUtil.sleep;

/**
 * @Projectname: MiniXYIot
 * @Filename: ProductController
 * @Author: FANSEA
 * @Data:2024/5/21 18:47
 */
@RestController
@RequestMapping("/product")
public class ProductController {
    @Autowired
    ProductsMapper productsMapper;

    @Autowired
    ProductsService productsService;

    @GetMapping("buy")
    @RedisLock(keyName = "'product:'+ #id")
    public Result buyProduct(@RequestParam Integer id,Integer count){
        // UPDATE products set stock = stock - 1 where id = 1 and stock>0
        productsMapper.buyProduct(id,count);
        //休眠10分钟
        /*try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }*/
        return Result.ok("购买成功!");
    }

    @PostMapping("add")
    public Result addProduct(@RequestBody Products products){
        // UPDATE products set stock = stock - 1 where id = 1 and stock>0
        boolean save = productsService.save(products);
        if (save){
            System.out.println("products.id = " + products.getId());
        }
        return Result.ok("新增成功!");
    }

    @GetMapping("detail")
    @Cacheable("productDetails")
    public Result detail(@RequestParam Integer id){
        Products product = productsService.getById(id);
        sleep(1000);
        return Result.ok(product);
    }
}
